package com.book.auth.handler;

import com.alibaba.fastjson.JSON;
import com.book.core.mode.R;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录时的失败处理
 *
 * @author hongmizfb
 * @date 2025/05/09
 */
@Component
public class LoginAuthenticationFailureHandler implements AuthenticationFailureHandler {


    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_OK);
        String message = "";
        //判断异常类型
        if (exception instanceof AccountExpiredException) {
            message = "token过期";
        } else if (exception instanceof BadCredentialsException) {
            message = "用户名或密码错误,登录失败!";
        } else if (exception instanceof CredentialsExpiredException) {
            message = "密码过期,登录失败!";
        } else if (exception instanceof DisabledException) {
            message = "账户被禁用,登录失败!";
        } else if (exception instanceof LockedException) {
            message = "账户被锁,登录失败!";
        } else if (exception instanceof InternalAuthenticationServiceException) {
            message = "账户不存在,登录失败!";
        }
        response.getWriter().write(JSON.toJSONString(R.err(message)));
    }
}
